<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta charset="utf-8" />
    <!--script src="https://unpkg.com/pdf-lib"></script-->
    
    <script src="pdf-lib.min.js"></script>
    <style type="text/css">
			.center-text {
				text-align: center;
			}
			
			.inputfile {
				opacity: 0;
			}

			.lab {
				border-radius: 10px;
				background-color: #cc99ff;
				font-family: 楷体;
				font-size: 24px;
			}
			.boxwidth200{
				width: 200px;
			}
		</style>
  </head>

  <body>
    <h3 class="center-text">提取Pdf图片</h3><br />
	<div class="center-text">
		<label for="resolution">图片文件名</label>	
		<input type="text" id="resolution" class="center-text boxwidth200" value="200" />
	</div>
	<div class="center-text">
		<input type="file" name="file1" id="file1" class="inputfile" accept="application/pdf" /><br />
		<label for="file1" class='lab'>打开Pdf文件</label><br /><br />
		<div class="center-text" id="img_info"></div>
	</div>
  </body>

  <script>
	//file extends blob
	function createURL(file) {
		var url = null;
		if (window.createObjectURL != undefined) {
			url = window.createObjectURL(file);
		} else if (window.URL != undefined) { // mozilla(firefox)  
			url = window.URL.createObjectURL(file);
		} else if (window.webkitURL != undefined) { // webkit or chrome  
			url = window.webkitURL.createObjectURL(file);
		}
		return url;
	};
	function downLoad(url,filename){
		var oA = document.createElement("a");
		oA.download = filename;// 设置下载的文件名，默认是'下载'
		oA.href = url;
		document.body.appendChild(oA);
		oA.click();
		oA.remove(); // 下载之后把创建的元素删除
	}
    const extractImagesFromPDF = async (files, outputPath) => {
		const url=createURL(files[0]);
		console.log(files[0], url);
		const pdfDoc = await PDFLib.PDFDocument.load(await fetch(url).then(res => res.arrayBuffer()));
		var index=0;
		for (const page of pdfDoc.getPages()) { 
			console.log("page:"+index,page,pdfDoc);
			const imagesOnPage = page.getImages();  
			for (const image of imagesOnPage) {  
				const imageData = await image.getImageData();  
				const imageBuffer = Buffer.from(imageData.data);  
				//images.push(imageBuffer); 
				const blob = new Blob(imageBuffer, { type: 'image/jpeg' });
				const downloadUrl = URL.createObjectURL(blob);
				downLoad(downloadUrl,index+++".jpg");
			}  
		}
	}
		const input_file=document.getElementById("file1");
		input_file.addEventListener('change', function(event){
			const resolution = document.getElementById("resolution").value-0;
			//console.log("resolution:"+resolution,typeof(resolution));
			if(isNaN(resolution)|| resolution<72||resolution>1200){
				alert("分辨率必须在72~1200之间");
				return;
			}
			extractImagesFromPDF(this.files);
		});
  </script>
</html>